<template>
    <el-select v-model="model" placeholder="请选择城市" style="width:100%" @change="change" :disabled="disabled">
        <el-option v-for="item in list" :key="item.cityId" :label="item.cityName" :value="item.cityId">
        </el-option>
    </el-select>
</template>

<script>
import { queryAllCityByProvinceId } from 'api/common';
import { mapGetters } from 'vuex';

export default {
    props: {
        value: {
            type: [String, Number],
            required: true
        },
        province: {
            type: [String, Number],
            required: true
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        model: {
            get() {
                if (this.list) {
                    if (this.list.some(item => item.cityId == this.value)) {
                        let cityObj = this.list.find((item) => {
                            return item.cityId === this.value;
                        });
                        this.$emit('getCityName',cityObj.cityName); 
                        return this.value;
                    } else {
                        this.$emit('input', '');
                        return '';
                    }
                } else {
                    return '';
                }
            },
            set(val) {
                this.$emit('input', val);
            }
        }
    },
    data() {
        return {
            list: null
        }
    },
    watch: {
        province(val) {
            this.getList();
            // this.$emit('input', '');
        }
    },
    created() {
        this.getList();
    },
    methods: {
        getList() {
            this.list = null;
            if (this.province) {
                let province = this.province;
                queryAllCityByProvinceId(this.province).then(res => {
                    if (res.data.content.length && this.province == province) {
                        this.list = res.data.content;
                        this.list.unshift({
                            cityId: '',
                            cityName: '请选择城市'
                        });
                    }
                }).catch(res=>{
                    setTimeout(()=>{
                        this.getList();
                    },Math.random().toFixed(3)*1500)
                });
            } else {
                this.$emit('input', '');
            }
        },
        change(val) {
            this.$emit('change', val);
        }
    }
}
</script>

<style>

</style>
